package com.binfenhulian.chinaenergy.ces.manage.core.url2io.handle;

import com.binfenhulian.chinaenergy.ces.core.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.*;

/**
 * Created by wanghjbuf on 2018/3/15.
 */
@Slf4j
@Component("com.binfenhulian.chinaenergy.ces.manage.core.url2io.handle.FileResultHandleThread")
public class FileResultHandleThread extends BaseResultHandleThread{

    //聚合大小，决定将多少个网页中爬取的正文内容保存在同一个文件里
    public int mTogether = 5;
    //文件名中的章节范围
    private String mFileNameMid = "";
    //写文件对象
    private static  WriterContentToFile mWriterContentToFile = new WriterContentToFile();

    @Override
    public void run() {
        mWriterContentToFile.write("title.txt", data.getTitle() + "    " + data.getUrl() + "\n");
        int i = (index + mTogether - 1) / mTogether;
        mFileNameMid = ((i - 1) * mTogether +1) + "-" + (i * mTogether);

        //内容持久化
        mWriterContentToFile.write("content_" + mFileNameMid + ".txt", "\n\r\n" + data.getTitle() + "\n" + data.getContent());
    }

    /**
     * 文件写入器
     */
    private static class WriterContentToFile {
        //文件输出流
        private FileOutputStream mFileOutputStream = null;
        //带缓冲的输出流
        private BufferedOutputStream mBufferedOutputStream =null;

        /**
         * 将内容写入到指定的文件
         *
         * @param fileName 文件名
         * @param content 要写入的内容
         */
        public void write(String fileName , String content) throws BaseException{

            try {
                //构造输出流
                mFileOutputStream = new FileOutputStream(new File(fileName) ,true);
                mBufferedOutputStream =new BufferedOutputStream(mFileOutputStream);
                //开始写入文件
                mBufferedOutputStream.write(content.getBytes());
                //刷新输出流并关闭输出流
                mBufferedOutputStream.flush();
                mBufferedOutputStream.close();

            } catch (FileNotFoundException e) {
                throw new BaseException("未找到指定文件,操作失败!", e);
            } catch (IOException e) {
                throw new BaseException("IO执行过程发生错误,操作失败!", e);
            }
        }
    }
}
